//
//  GYOAuthViewController.swift
//  Weibo
//
//  Created by vane on 16/8/10.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class GYOAuthViewController: UIViewController {
    
    
    override func loadView() {
        
        view = webView
        
        guard let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirect_uri)")else{
            
            return
    
        }
        webView.delegate = self
        
        let request = NSURLRequest(URL: url)

        webView.loadRequest(request)

        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
    }
    private func setupUI(){
        
        view.backgroundColor = UIColor.whiteColor()
        
        setupNav()
    }
    private func setupNav(){
        
        navigationItem.title = "微博登录"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelAction")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFillAction")
        

    }
    
    @objc private func cancelAction(){
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func autoFillAction(){
        
//        print("zzz")

    let js = "document.getElementById('userId').value='\(WBName)',document.getElementById('passwd').value ='\(WBPassWd)'"
        
    webView.stringByEvaluatingJavaScriptFromString(js)
    
    }
    
    private lazy var webView:UIWebView = UIWebView()
}
extension GYOAuthViewController:UIWebViewDelegate{
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        

        //absoluteString 把url变成字符串
        if let urlStr = request.URL?.absoluteString where urlStr.hasPrefix(WBRedirect_uri){
            
            // query 请求参数
            if let query = request.URL?.query{
                //截取字符串 获取code
                let code = query.substringFromIndex("code=".endIndex)
                
//                print("获取code:\(code)")
                GYUserAccountViewModel.sharedTools.getAccessToken(code, finish: { (isSuccess) -> () in
                    
                    if !isSuccess {
                    print("请求失败")
                    }
                    print("请求成功")
                    
                    self.dismissViewControllerAnimated(true, completion: { () -> Void in
                        
                        SVProgressHUD.dismiss()
                        NSNotificationCenter.defaultCenter().postNotificationName(WBNOTIFICATIONCENTERNAME, object: "login")
                        
                    })
                  

                })
            }
            
        }
        
        return true
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
         SVProgressHUD.dismiss()
    }

    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }

    
}
